package cn.bytepulse.pojo;


import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author jiejiebiezheyang
 * @since 2024-02-02 19:00
 */
public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {

    private final byte[] cachedBody;

    public CachedBodyHttpServletRequest(HttpServletRequest request) throws IOException {
        super(request);
        // 读取原始请求体并缓存
        InputStream requestInputStream = request.getInputStream();
        this.cachedBody = requestInputStream.readAllBytes();
    }

    @Override
    public ServletInputStream getInputStream() {
        // 返回缓存的请求体流
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(cachedBody);
        return new ServletInputStream() {
            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public void setReadListener(ReadListener listener) {
                throw new UnsupportedOperationException();
            }
        };
    }

    @Override
    public BufferedReader getReader() {
        // 返回缓存的请求体Reader
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(cachedBody);
        return new BufferedReader(new InputStreamReader(byteArrayInputStream, StandardCharsets.UTF_8));
    }

    /**
     * 获取缓存的请求体（字节数组）
     */
    public byte[] getCachedBody() {
        return cachedBody;
    }

    /**
     * 获取缓存的请求体（字符串）
     */
    public String getCachedBodyAsString() {
        return new String(cachedBody, StandardCharsets.UTF_8);
    }

    /**
     * 修改请求体（字节数组）
     */
    public void setCachedBody(byte[] newBody) {
        System.arraycopy(newBody, 0, cachedBody, 0, newBody.length);
    }

    /**
     * 修改请求体（字符串）
     */
    public void setCachedBody(String newBody) {
        byte[] newBodyBytes = newBody.getBytes(StandardCharsets.UTF_8);
        System.arraycopy(newBodyBytes, 0, cachedBody, 0, newBodyBytes.length);
    }
}